package com.atguigu.Mytest;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SeamphroeDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);


        for (int i = 0; i < 6; i++) {
            int cardnumber = i;
            new Thread(()->{
                boolean flag = false;
                try {
                    semaphore.acquire();
                    flag = true;
                    System.out.println(Thread.currentThread().getName()+"抢到了车位："+cardnumber);
                    try { TimeUnit.SECONDS.sleep(new Random().nextInt(4)+1); } catch (InterruptedException e) { e.printStackTrace(); }
                    System.out.println(Thread.currentThread().getName()+"离开了车位"+cardnumber);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (flag){
                        semaphore.release();
                    }
                }
            },String.valueOf(i)).start();
        }


    }
}
